﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Tomahawk.Runtime.Console
{
    public abstract class ConsoleCommand
    {
        public abstract string GetName();
        public abstract string GetHelp();
        public abstract string Execute(string[] parameters);

        protected static Dictionary<string, ConsoleCommand> commandTable;
        public static bool IsCommandTableBuilt
        {
            get { return commandTable != null && commandTable.Count > 0; }
        }
        public static void BuidCommandTable()
        {
            commandTable = new Dictionary<string, ConsoleCommand>();
            Type commandType = typeof(ConsoleCommand);

            #if !XBOX
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                Type[] types = assembly.GetTypes();

                foreach (Type type in types)
                {
                    if (type.IsSubclassOf(commandType))
                    {
                        ConsoleCommand command = Activator.CreateInstance(type) as ConsoleCommand;
                        commandTable.Add(command.GetName(), command);
                    }
                }
            }
            #endif
        }
        public static string Execute(string command, string[] parameters)
        {
            ConsoleCommand consoleCommand;
            if (commandTable.TryGetValue(command, out consoleCommand))
            {
                return consoleCommand.Execute(parameters);
            }
            else
            {
                return "Unknown command";
            }
        }
    }
}
